﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
using foursquare.Location;

namespace PhoneVoyage.Services
{
    /// <summary>
    /// Calls OpenCellId.org to get lat/long from cell tower data.
    /// </summary>
    /// <remarks>This is here for the article's sake, but isn't used.</remarks>
    internal class OpenCellIdService
    {
        private const string Open_Cell_Id_Uri = "http://www.opencellid.org/cell/get?key={0}&mcc={1}&mnc={2}&cellid={3}&lac={4}";

        internal GeoLocation GetCellTowerLocation(CellTower towerDetails)
        {
            XDocument doc = XDocument.Load(string.Format(Open_Cell_Id_Uri, new object[]{
                //Settings.OpenCellIDApiKey,
                towerDetails.MobileCountryCode, 
                towerDetails.MobileNetworkCode, 
                towerDetails.TowerId,
                towerDetails.LocationAreaCode
                }));

            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            using (System.Xml.XmlReader reader = doc.CreateReader())//;
            {
                reader.MoveToContent();
                xmlDoc.Load(reader);
                System.Globalization.NumberFormatInfo nfi = new System.Globalization.CultureInfo("en-US", false).NumberFormat;

                GeoLocation location = new GeoLocation
                {
                    Latitude = double.Parse(xmlDoc.DocumentElement.SelectSingleNode("/rsp/cell/@lat").Value, nfi),
                    Longitude = double.Parse(xmlDoc.DocumentElement.SelectSingleNode("/rsp/cell/@lon").Value, nfi)
                }; // Added by JoP

                if (location.Latitude == 0 && location.Longitude == 0)
                {
                    return GeoLocation.Empty;
                }

                return location;
            }
        }
    }
}